package com.example.train.controller;

import com.example.train.common.base.model.ResponseBase;
import com.example.train.common.base.model.ResponsePage;
import com.example.train.model.SysRole;
import com.example.train.model.vo.SysRoleVO;
import com.example.train.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/role")
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @PostMapping
    public ResponseBase<Integer> add(@RequestBody @Valid SysRole sysRole){
        Integer insert = sysRoleService.insert(sysRole);
        if (insert == null) {
            return ResponseBase.failed("角色已存在");
        }
        return ResponseBase.success(insert);
    }

    @PutMapping
    public ResponseBase<Integer> update(@RequestBody SysRole sysRole){
        int i = sysRoleService.updateByPrimaryKeySelective(sysRole);
        if (i == 0) {
            return ResponseBase.failed("不存在该数据");
        }else{
            return ResponseBase.success(i);
        }
    }

    @DeleteMapping("/{id}")
    public ResponseBase<Integer> delete(@PathVariable Long id){
        int i = sysRoleService.deleteByPrimaryKey(id);
        if (i == 0) {
            return ResponseBase.failed("不存在该数据");
        }else{
            return ResponseBase.success(i);
        }
    }

    @GetMapping("/{id}")
    public ResponseBase<SysRole> get(@PathVariable Long id){
        SysRole sysRole = sysRoleService.selectByPrimaryKey(id);
        if (sysRole == null) {
            return ResponseBase.failed("不存在该数据");
        }
        return ResponseBase.success(sysRole);
    }

    @GetMapping("/list")
    public ResponseBase<ResponsePage<SysRole>> list(@RequestParam(defaultValue = "1") int pageNum,
                                                    @RequestParam(defaultValue = "${settings.pageHelper.pageSize}") int pageSize){
        List<SysRole> list = sysRoleService.selectAll(pageNum, pageSize);
        return ResponseBase.success(ResponsePage.restPage(list));
    }

    @GetMapping("/listRoleForAdmin")
    public ResponseBase<List<SysRoleVO>> listRoleForAdmin() {
        List<SysRole> list = sysRoleService.selectAll(null, null);
        List<SysRoleVO> collect = list.stream().filter(r -> r.getStatus() == 1).map(r -> {
            SysRoleVO roleVO = new SysRoleVO();
            BeanUtils.copyProperties(r, roleVO);
            return roleVO;
        }).collect(Collectors.toList());
        return ResponseBase.success(collect);
    }

}
